package cn.mesmile.drools.service.impl;

import cn.mesmile.drools.entity.*;
import cn.mesmile.drools.service.RulesService;
import cn.mesmile.drools.utils.KieSessionUtils;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zb
 * @date 2021/7/25 23:58
 * @Description
 */
@Service
public class RulesServiceImpl implements RulesService {

    private final KieBase kieBase;

    public RulesServiceImpl(KieBase kieBase) {
        this.kieBase = kieBase;
    }

    @Override
    public void rule() {
        KieSession kieSession = kieBase.newKieSession();

        // 构造订单对象，设置原始价格，由规则引擎根据优惠规则计算优惠后的价格
        Student student = new Student();
        student.setAge(8);
        student.setName("test");
        Order order = new Order();
        order.setOriginalPrice(100.0);

        // 将order对象插入到工作内存中 将数据提供给规则引擎，规则引擎会根据提供的数据进行规则匹配
        kieSession.insert(student);
        kieSession.insert(order);

        // 执行规则引擎
        kieSession.fireAllRules();
        // 关闭会话
        kieSession.dispose();
    }

    @Override
    public Calculation calculate(Calculation calculation) {
        KieSession kieSession = kieBase.newKieSession();
        kieSession.insert(calculation);
        kieSession.fireAllRules();
        kieSession.dispose();
        return calculation;
    }

    @Override
    public CreditCardApplyInfo creditCardApply(CreditCardApplyInfo creditCardApplyInfo){
        KieSession session = kieBase.newKieSession();
        session.insert(creditCardApplyInfo);
        session.fireAllRules();
        session.dispose();
        return creditCardApplyInfo;
    }

    @Override
    public List<String> insuranceInfoCheck(InsuranceInfo insuranceInfo) throws Exception {
        // 从指定目录读取  决策表
        KieSession session = KieSessionUtils.getKieSessionFromXLS("D:\\rules.xls");
        // 设置 组名为“sign” 的组获取焦点
        session.getAgenda().getAgendaGroup("sign").setFocus();

        session.insert(insuranceInfo);
        // 全局变量
        List<String> listRules = new ArrayList<>();
        session.setGlobal("listRules", listRules);

        session.fireAllRules();

        return listRules;
    }

}
